package com.erp.framework.util;

import java.util.Properties;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import com.erp.framework.SimpleConstants;
import com.erp.framework.util.logger.Logger;

public class MailUtil implements SimpleConstants{

    private String emailServer;
    private String emailUserLogin;
    private String emailUserPwd;

    public void setEmailServer(String emailServer) {

        this.emailServer = emailServer;
    }

    public void setEmailUserLogin(String emailUserLogin) {

        this.emailUserLogin = emailUserLogin;
    }

    public void setEmailUserPwd(String emailUserPwd) {

        this.emailUserPwd = emailUserPwd;
    }

    public String getEmailServer() {

        return this.emailServer;
    }

    public String getEmailUserLogin() {

        return this.emailUserLogin;
    }

    public MailUtil() {

    }

    public MailUtil(String emailServer, String emailUserLogin, String emailUserPwd) {

        this.emailServer = emailServer;
        this.emailUserLogin = emailUserLogin;
        this.emailUserPwd = emailUserPwd;
    }

    public void sendEmail(String senderAddr, String senderName, String[] toAddress, String subject, String content)
            throws Exception {

        if (toAddress == null) {
            Logger.warn(this, "sendEmail(), toAddress is null!");
            return;
        }

        if (toAddress.length <= 0) {
            Logger.warn(this, "sendEmail(), No toAddress is received!");
            return;
        }

        try {
            Properties props = new Properties();
            props.setProperty("mail.transport.protocol", "smtp");
            props.setProperty("mail.host", this.emailServer);
            props.setProperty("mail.user", this.emailUserLogin);
            props.setProperty("mail.password", this.emailUserPwd);

            Session mailSession = Session.getDefaultInstance(props, null);
            Transport transport = mailSession.getTransport();

            MimeMessage mail = new MimeMessage(mailSession);

            InternetAddress[] to = new InternetAddress[toAddress.length];
            for (int i = 0; i < toAddress.length; i++) {
                to[i] = new InternetAddress(toAddress[i]);
            }

            mail.setSubject(subject);
            mail.setContent(content, "text/plain");
            mail.setSentDate(new java.util.Date(System.currentTimeMillis()));
            mail.setFrom(new InternetAddress(senderAddr, senderName));
            mail.setRecipients(Message.RecipientType.TO, to);

            transport.connect();
            transport.sendMessage(mail, mail.getRecipients(Message.RecipientType.TO));
            transport.close();
        } catch (Exception e) {
            // Logger.logExceptions(this, e);
            throw new Exception(e.toString());
        }
    }
}